"""
    Easy way to include the google analytics script code.
    Usage:
        Configure your CACHE_MIDDLEWARE_KEY_PREFIX and your cache
        {% load urchin %}
        Just put before the </body> of your page {% urchin "your-urchin-code" %}
        
        You can force the application to get your urchin code from the settings using
        settings as the urchin code. The application will try to find a setting.URCHIN_CODE
"""
# Author : aaloy - Adapted from http://www.djangosnippets.org/snippets/457/ by blinks
# to add cache key and include the new analytics code.
from django import template
from django.core.cache import cache
from django.conf import settings
register = template.Library()

def urchin (uacct):
    if uacct == "settings":
        uacct = settings.URCHIN_CODE
    cache_key = '%surchin'%settings.CACHE_MIDDLEWARE_KEY_PREFIX
    urchin_code = cache.get(cache_key)
    if urchin_code == None:
        if not settings.DEBUG:
            base=u"""
                    <!-- codigo google analytics -->
                    <script type="text/javascript">
                        var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
                        document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
                    </script>
                    """
            codigo=u"""
                    <script type="text/javascript">
                        var pageTracker = _gat._getTracker("%(uacct)s");
                        pageTracker._initData();
                        pageTracker._trackPageview();
                    </script>""" % {'uacct':uacct}
            urchin_code = base + u"\n"+codigo
            cache.set(cache_key, urchin_code, 86400)
        else:
            urchin_code= u"<!-- aqui ira el codigo de analytics en produccion %(uacct)s -->"  % {'uacct':uacct}
    return urchin_code
register.simple_tag(urchin)